package com.intpro.demo.Utils;

import com.intpro.demo.DAO.AdminUser;
import com.intpro.demo.DAO.Role;
import com.intpro.demo.DAO.User;
import com.intpro.demo.Service.AdminService;
import com.intpro.demo.Service.TokenService;
import com.intpro.demo.Service.UserService;
import com.intpro.demo.Utils.MyAnnotations.Authorization;
import java.lang.reflect.Method;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

@Component
public class AuthorizedInterceptor implements HandlerInterceptor
{

	@Autowired
	private UserService userService;
	@Autowired
	private AdminService adminService;
	@Autowired
	private TokenService tokenService;

	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object o) throws CodeException
	{
		if (!(o instanceof HandlerMethod))
		{
			return true;
		}
		HandlerMethod handlerMethod = ((HandlerMethod) o);

		Method method = handlerMethod.getMethod();
		//获取方法上的Authorization注解
		Authorization tokenValid = method.getAnnotation(Authorization.class);
		//如果方法上有Authorization注解
		if (tokenValid != null)
		{

			String token = request.getHeader("token");
			if (token == null)
			{
				throw CodeException.AuthorizationErr();
			}
			long id = -1;
			try
			{
				id = AESToken.verifyToken(token);
			} catch (Exception e)
			{
				throw CodeException.TokenErr();
			}
			if (!tokenService.checkToken(id, token))
			{
				throw CodeException.TokenErr();
			}
			if (tokenValid.role().equals(Role.admin))
			{
				AdminUser user = adminService.getUserById(id);
				if (user == null)
				{
					throw CodeException.TokenErr();
				}
				request.setAttribute("admin", user);
			} else
			{
				User user = userService.getUserById(id);
				if (user == null)
				{
					throw CodeException.TokenErr();
				}
				request.setAttribute("user", user);
			}
			return true;
		}

		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request,
			HttpServletResponse response, Object o, ModelAndView modelAndView)
			throws Exception
	{
	}

	@Override
	public void afterCompletion(HttpServletRequest request,
			HttpServletResponse response, Object o, Exception e) throws Exception
	{
	}
}
